package com.example.hello.config;

import com.example.hello.security.JwtAuthenticationFilter;
import com.example.hello.security.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

  private final UserDetailsServiceImpl userDetailsService;
  
  @Autowired
  private CorsFilter corsFilter;

  @Autowired
  public SecurityConfig(@Lazy UserDetailsServiceImpl userDetailsService) {
    this.userDetailsService = userDetailsService;
  }

  @Autowired
  private JwtAuthenticationFilter jwtAuthenticationFilter;

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Bean
  public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
    return authConfig.getAuthenticationManager();
  }

  @Bean
  public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setUserDetailsService(userDetailsService);
    provider.setPasswordEncoder(passwordEncoder);
    return provider;
  }

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // 开启跨域
        .cors(cors -> cors.configure(http))
        .csrf(csrf -> csrf.disable())
        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(auth -> auth
            // 公开接口 - 无需认证
            .requestMatchers("/api/auth/login").permitAll()
            .requestMatchers("/api/auth/register").permitAll()
            .requestMatchers("/api/test/**").permitAll()
            .requestMatchers("/api-docs/**").permitAll()
            .requestMatchers("/swagger-ui/**").permitAll()
            .requestMatchers("/swagger-ui.html").permitAll()

            // Swagger相关路径 - 全部放行
            .requestMatchers("/error").permitAll() // 错误页面
            .requestMatchers("/actuator/**").permitAll() // 健康检查

            // 需要认证的接口
            .requestMatchers("/api/user/**").authenticated() // 用户相关接口需要认证
            .requestMatchers("/api/admin/**").hasRole("ADMIN") // 管理员接口需要ADMIN角色
            
            // 景点分类相关接口
            .requestMatchers("/api/category/all").permitAll() // 获取所有景点类别的接口允许公开访问
            .requestMatchers("/api/category/{categoryId}").permitAll() // 获取单个景点类别详情允许公开访问
            .requestMatchers("/api/category/list").permitAll() // 分页获取景点类别列表允许公开访问
            .requestMatchers("/api/category/**").authenticated() // 其他景点类别接口需要认证
            
            // 景点信息相关接口
            .requestMatchers("/api/attraction/{attractionId}").permitAll() // 获取景点详情允许公开访问
            .requestMatchers("/api/attraction/list").permitAll() // 分页获取景点列表允许公开访问
            .requestMatchers("/api/attraction/**").authenticated() // 其他景点信息接口需要认证
            
            // 评论相关接口
            .requestMatchers("/api/comment/{commentId}").permitAll() // 获取评论详情允许公开访问
            .requestMatchers("/api/comment/attraction/{attractionId}").permitAll() // 获取景点评论列表允许公开访问
            .requestMatchers("/api/comment/list").permitAll() // 获取所有留言列表允许公开访问
            .requestMatchers("/api/comment/top/{attractionId}").permitAll() // 获取置顶评论允许公开访问
            .requestMatchers("/api/comment/**").authenticated() // 其他评论相关接口需要认证

            // 文件上传接口需要认证
            .requestMatchers("/api/file/avatar").authenticated()
            .requestMatchers("/api/file/attraction").authenticated()
            .requestMatchers("/api/file/**").authenticated()

            // 密码重置相关接口
            .requestMatchers("/api/password/**").permitAll()

            // 其他所有请求需要认证
            .anyRequest().authenticated())

        // 添加JWT过滤器
        .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
        // 添加CORS过滤器
        .addFilterBefore(corsFilter, JwtAuthenticationFilter.class)

        // 异常处理
        .exceptionHandling(exceptions -> exceptions
            .authenticationEntryPoint((request, response, authException) -> {
              response.setContentType("application/json;charset=UTF-8");
              response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
              response.getWriter().write("{\"code\":401,\"message\":\"未授权：" + authException.getMessage() + "\"}");
            })
            .accessDeniedHandler((request, response, accessDeniedException) -> {
              response.setContentType("application/json;charset=UTF-8");
              response.setStatus(HttpServletResponse.SC_FORBIDDEN);
              response.getWriter()
                  .write("{\"code\":403,\"message\":\"拒绝访问：" + accessDeniedException.getMessage() + "\"}");
            }));

    return http.build();
  }
}